<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .container {
      width: 1000px;
      position: absolute;
      top: 800px;
      left: 50%;
      transform: translateX(-50%);
    }

    .hero-list {
      margin: 0 -10px;
      overflow: hidden;
    }

    .item {
      float: left;
      width: 10%;
      padding: 0 10px;
      box-sizing: border-box;
    }

    .item img {
      width: 100%;
    }

    .item p {
      text-align: center;
      margin-top: 0;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  </style>
</head>

<body>
  <!-- https://api.xiaohigh.com/lol -->
  <div class="container">
    <h2>英雄列表</h2>
    <hr>
    <div class="hero-list">

    </div>
  </div>

  <script>
    //获取 hero-list 元素
    let heroList = document.querySelector('.hero-list');
    //是否正在加载中
    let isLoading = false;

    function loadHero() {
      if(isLoading) return;
      //设置状态为加载中...
      isLoading = true;
      let xhr = new XMLHttpRequest();
      xhr.open('get', 'http://api.xiaohigh.com/lol');
      xhr.responseType = 'json';
      xhr.send();
      xhr.onload = function () {
        //遍历响应体的英雄数据
        xhr.response.forEach(item => {
          //创建 div 元素
          let div = document.createElement('div');
          //添加类名
          div.classList.add('item');
          //创建 img
          let img = document.createElement('img');
          //设置 img 的 src
          img.src = item.avatar;
          //创建 p 元素
          let p = document.createElement('p');
          //设置 p 元素的文本
          p.innerHTML = item.name;
          //组装
          div.append(img);
          div.append(p);
          heroList.append(div);
        })
        //设置状态为未加载
        isLoading = false;
      }

    }

    //绑定 window.onscroll 事件
    window.onscroll = function(){
      //检测 heroList 元素是否进入可视区域
      let data = heroList.getBoundingClientRect();
      if(data.top > 0 && data.top < document.documentElement.clientHeight){
        //加载英雄数据
        loadHero();
      }
    }

  </script>
</body>

</html>